<template>
  <div class="procure-outbound-put">
    <div class="info">
      <div>
        <div class="left">
          <h3 class="mr46 f16 orange">待出库</h3>
          <p class="creater mr40">制单人：{{ detail.createBy || "-" }}</p>
          <p class="mr40">制单时间：{{ detail.createTime || "-" }}</p>
          <p>出库编码：{{ detail.deliveryNo || "-" }}</p>
        </div>
        <div class="right">
          <!-- <el-button type="info" plain @click="$router.push({ path: '/procure/outbound', query: {} })">返回</el-button> -->
        </div>
      </div>
    </div>

    <el-container class="content">
      <el-aside>
        <header>
          <div class="supper">
            <p>
              出库仓：<b>{{ list.length > 0 ? list[0].warehouseName || "-" : "-" }}</b>
            </p>
          </div>
        </header>

        <!-- 商品列表 -->
        <div class="products-list" style="overflow-x: auto">
          <div class="my-table" style="min-width: 1300px">
            <div class="table-header">
              <div>
                <div>
                  <div class="col1">商品信息</div>
                  <div class="col2">数量</div>
                  <div class="col3">预计出库件数</div>
                  <div class="col4">单位</div>
                  <div class="col5">实际出库数量</div>
                  <div class="col6">实际出库件数</div>
                  <div class="col7">仓库</div>
                </div>
              </div>
            </div>

            <div class="table-body" v-if="list.length > 0">
              <div class="list-item" v-for="(item, index) in list" :key="index">
                <div>
                  <div class="col1">
                    <div>
                      <div class="left">
                        <img :src="item.mainPicUrl" alt="" />
                      </div>
                      <div class="right">
                        <h3 class="name text-break">{{ item.productName || "-" }}</h3>
                        <p style="white-space: break-spaces">
                          <!-- {{ getSpes(item.properties) }} -->
                          {{ item.skuSpecification }}
                        </p>
                        <p>SKU编码：{{ item.code || "-" }}</p>
                        <p>ID:{{ item.productId || "-" }}</p>
                      </div>
                    </div>
                  </div>
                  <div class="col2">
                    {{ item.inventoryQuantity || "-" }}
                    <!-- <el-input-number
                    :min="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.inventoryQuantity"
                    oninput="value=value.replace(/[^0-9]/g, '')"
                  ></el-input-number> -->
                  </div>
                  <div class="col3">
                    {{ item.inventoryPartQuantity || "-" }}
                    <!-- <el-input-number
                    :min="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.inventoryPartQuantity"
                    oninput="value=value.replace(/[^0-9]/g, '')"
                  ></el-input-number> -->
                  </div>
                  <div class="col4">
                    {{ getName(item.productUnit) || "-" }}
                    <!-- {{ item.productUnit || "-" }} -->
                  </div>
                  <div class="col5">
                    {{ item.deliveryQuantity || "-" }}
                    <!-- <el-input-number
                    :min="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.deliveryQuantity"
                    oninput="value=value.replace(/[^0-9]/g, '')"
                  ></el-input-number> -->
                  </div>
                  <div class="col6">
                    {{ item.deliveryPartQuantity || "-" }}
                    <!-- <el-input-number
                    :min="0"
                    controls-position="right"
                    style="width: 100px"
                    v-model="item.deliveryPartQuantity"
                    oninput="value=value.replace(/[^0-9]/g, '')"
                  ></el-input-number> -->
                  </div>
                  <div class="col7">{{ item.warehouseName || "-" }}</div>
                </div>
                <div class="tips">
                  <p class="label">备注</p>
                  <!-- <el-input maxlength="200" v-model="item.remark" placeholder="请输入"></el-input> -->
                  <RemarkEditor v-model="item.remark" />
                </div>
              </div>
            </div>
            <div v-else style="display: flex; justify-content: center; width: 100%">
              <el-empty description="暂无数据" />
            </div>
          </div>
        </div>
      </el-aside>
      <el-main width="300px">
        <!-- 用户信息---只有是订单出库单才显示 -->
        <div class="sh-info" v-if="$route.query.deliveryType === 2">
          <p>用户信息</p>
          <el-form :model="form" ref="formRef" label-width="auto" style="max-width: 600px">
            <el-form-item label="姓名">
              <span>{{ detail.customerName || "-" }}</span>
            </el-form-item>
            <el-form-item label="电话">
              <span>{{ detail.customerMobileCode || "-" }}</span>
            </el-form-item>
          </el-form>
        </div>
        <div class="ck-time mb20">
          <p>期望出库日期</p>
          <el-date-picker
            v-model="ckTime"
            value-format="YYYY-MM-DD  HH:mm:ss"
            type="datetime"
            placeholder="请选择"
            style="width: 100%"
          />
        </div>
        <div class="ps-people">
          <p>配送人员</p>
          <div>
            <el-select filterable v-model="psValue" placeholder="请选择" style="width: 100%" @change="psChange">
              <el-option
                v-for="item in psList"
                :key="item.partnerId"
                :label="item.name + '-' + item.contacts"
                :value="item.partnerId"
              />
            </el-select>
            <el-button type="primary" plain @click="openAdd">新建配送人</el-button>
          </div>
        </div>
        <div class="divider"></div>

        <!-- 关联借调客户信息 -->
        <SecondCustomer
          ref="secondCustomerRef"
          :isEdit="true"
          :isEditRemark="true"
          :detail="detail"
          title="关联客户信息"
          remarkTitle="关联备注说明"
          dialogTitle="添加关联客户"
          actionTips="确定要取消关联客户信息？"
        />
        <div class="divider"></div>

        <!-- 收货信息 -->
        <div class="sh-info">
          <p class="sh-address">
            <span>收货信息</span>
            <el-button
              v-if="$route.query.deliveryType === '2'"
              type="primary"
              link
              size="small"
              @click="
                () => {
                  optionInfo.customerId = detail.customerId;
                  optionInfo.selectedObj = {
                    receivingAddressId: form.receivingAddressId,
                    receivingName: form.receivingName,
                    receivingMobile: form.receivingMobile,
                    receivingAreaIds: String(form.receivingAreaIds),
                    receivingAddress: form.receivingAddress
                  };
                  optionInfo.isShow = true;
                }
              "
            >
              地址管理
            </el-button>
          </p>
          <el-form
            :model="form"
            ref="formRef"
            label-width="auto"
            style="max-width: 600px"
            :disabled="$route.query.deliveryType === '3' || $route.query.deliveryType === '2'"
          >
            <el-form-item label="收货人" prop="receivingName" :rules="{ required: true, message: '请选择', trigger: ['blur'] }">
              <el-input v-model="form.receivingName" placeholder="请输入" />
            </el-form-item>
            <el-form-item
              label="手机号"
              prop="receivingMobile"
              :rules="[
                { required: true, message: '请输入', trigger: ['blur'] },
                { pattern: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
              ]"
            >
              <el-input v-model="form.receivingMobile" placeholder="请输入" />
            </el-form-item>
            <el-form-item
              prop="receivingAreaIds"
              label="收货地址"
              :rules="{ required: true, message: '请选择', trigger: ['blur'] }"
            >
              <el-cascader
                placeholder="请选择"
                class="pb10"
                ref="cascaderRef"
                v-model="form.receivingAreaIds"
                :options="mapList"
                :props="{
                  expandTrigger: 'hover', //次级菜单的展开方式
                  label: 'name',
                  value: 'id'
                }"
                @change="handleChange"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item
              prop="receivingAddress"
              label="详细地址"
              :rules="{ required: true, message: '请输入', trigger: ['blur'] }"
            >
              <el-input
                v-model="form.receivingAddress"
                placeholder="请输入"
                oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="divider"></div>

        <!-- 入库备注 -->
        <div class="ck-tips">
          <p class="label">出库备注</p>
          <!-- <el-input maxlength="200" v-model="detail.remark" :rows="10" type="textarea" placeholder="请输入" /> -->
          <RemarkEditor v-model="detail.remark" @submit="saveRemarkFun" @cancel="cancelRemarkFun" />
        </div>
      </el-main>
    </el-container>

    <!-- 操作按钮栏 -->
    <div class="action-wrap">
      <el-button type="info" plain @click="submit(2)">撤销出库</el-button>
      <el-button type="primary" @click="submit(1)">确认出库</el-button>
    </div>

    <!-- 确认暂存的list会清空 -->
    <ActionSubmitDialog
      v-model:isOpen="_isOpenClear"
      :message="'您正在重新选择出库仓，当前商品信息将被重置，重新添加商品，请问是否继续当前操作？'"
      :submitBtnText="'继续前往'"
      @submit="returnSubmitClear"
    />

    <!-- 新建配送人 -->
    <el-dialog
      v-model="dialogVisible"
      :title="'新建配送人'"
      width="500"
      align-center
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :before-close="closeAdd"
    >
      <div class="form-wrap">
        <el-form :model="form2" ref="form2Ref" label-width="auto" style="max-width: 600px">
          <el-form-item prop="name" label="配送人名" :rules="{ required: true, message: '请输入', trigger: ['blur'] }">
            <el-input
              v-model="form2.name"
              placeholder="请输入"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
          <el-form-item
            prop="phone"
            label="手机号"
            :rules="[
              { required: true, message: '请输入', trigger: ['blur'] },
              { pattern: /^1[2345789]\d{9}$/, message: '请输入格式正确的手机号' }
            ]"
          >
            <el-input
              v-model="form2.phone"
              placeholder="请输入"
              oninput="value = value.replace(/[!|@|#|$|%|^|&|*|+|~|`|,|.|！|￥]/g, '')"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer" style="text-align: center">
          <el-button @click="closeAdd">取消</el-button>
          <el-button type="primary" @click="addSubmit">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 地址管理 -->
    <addressManage :optionInfo="optionInfo" @close="closeAddress" @submit="submitAddress" />
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from "vue";
import SearchForm from "@/components/SearchForm";
import { Search, RefreshRight } from "@element-plus/icons-vue";
import { getSuppliers } from "@/apis/products/specifications";
import moment from "moment";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import { getTempProductSkuList, newInboundOrder, delTempProductSku } from "@/apis/procure/entry";
import { ListPage } from "@/apis/procure/warehouse";
import { ElMessage, ElMessageBox } from "element-plus";
import useCodeArrStore from "@/store/modules/select";
import ActionSubmitDialog from "@/components/ActionSubmitDialog";
import china from "@/utils/china.json";
import addressManage from "./components/addressManage";
import {
  createOtherDeliveryOrderDetail,
  delivery,
  deliveryManQueryList,
  addDeliveryMan,
  saveRemark
} from "@/apis/procure/outbound";
import RemarkEditor from "@/components/RemarkEditor";
import SecondCustomer from "./components/secondCustomer.vue";

const secondCustomerRef = ref();
const houseList = ref([]); //出库仓下拉数据
const houseValue = ref(""); //选中的出库仓
const list = ref([]);
const detail = ref([]);
const pagination = ref({
  page: 1,
  size: 10,
  sizes: [10, 20, 30, 40, 50],
  total: 0
});
const storeList = ref([]); //收货仓库下拉数据
const ckTime = ref("");
const textarea = ref("");
const userInfo = ref({});
const _isOpenClear = ref(false);
const psList = ref([{ label: "配送人A", value: 1 }]); //配送人员下拉数据
const psValue = ref(null); //选中的配送人员id
const psName = ref(null); //选中的配送人员name
const form = ref({}); //收货信息表单数据
const formRef = ref();
const form2 = ref({}); //新建配送人表单数据
const form2Ref = ref();
const mapList = ref(china);
const dialogVisible = ref(false);
const optionInfo = ref({ isShow: false }); //地址管理弹窗

onMounted(async () => {
  const res = await getSuppliers();
  houseList.value = res.data;
  userInfo.value = {
    name: JSON.parse(localStorage.getItem("userinfo")).tenantName,
    time: moment().format("YYYY/MM/DD HH:mm:ss")
  };

  const res2 = await ListPage({ page: 1, size: 9999 }); //入库仓
  storeList.value = res2.data.records;

  const res3 = await deliveryManQueryList({ deliveryId: route.query.deliveryId }); //配送人列表
  psList.value = res3.data;

  if (route.query.factoryId) houseValue.value = route.query.factoryId;

  getList();
});

//取消保存备注信息
const cancelRemarkFun = () => {
  detail.value.remark = JSON.parse(JSON.stringify(_remark.value));
};

//及时保存备注信息
const saveRemarkFun = () => {
  saveRemark({ deliveryId: route.query.deliveryId, remark: detail.value.remark })
    .then(res => {
      if (res.code === 200) {
        ElMessage({
          message: "备注信息保存成功~",
          type: "success"
        });
      }
    })
    .finally(() => {
      // getList();
    });
};

const psChange = val => {
  const obj = psList.value.find(item => item.partnerId === val);
  psName.value = obj?.name + "-" + obj?.contacts;
};

//关闭地址管理弹窗
const closeAddress = () => {
  optionInfo.value.isShow = false;
};
//地址管理submit回调
const submitAddress = selectObj => {
  optionInfo.value.isShow = false;
  // console.log("选中的地址===", selectObj);

  form.value = {
    receivingAddressId: selectObj.receivingAddressId,
    receivingName: selectObj.receivingName,
    receivingMobile: selectObj.receivingMobile,
    receivingAreaIds: selectObj.receivingAreaIds ? selectObj.receivingAreaIds.split(",").map(Number) : [],
    receivingAddress: selectObj.receivingAddress
  };
};

//打开新建配送人弹窗
const openAdd = () => {
  dialogVisible.value = true;
};
//关闭新建配送人弹窗
const closeAdd = () => {
  form2Ref.value.resetFields();
  dialogVisible.value = false;
};

//确认新建配送人
const addSubmit = () => {
  form2Ref.value.validate((valid, fields) => {
    if (valid) {
      addDeliveryMan({
        ...form2.value,
        deliveryId: route.query.deliveryId
      }).then(async res => {
        if (res.code === 200) {
          ElMessage({
            message: "配送人创建成功",
            type: "success"
          });
          const res3 = await deliveryManQueryList({ deliveryId: route.query.deliveryId }); //配送人列表
          psList.value = res3.data;
          closeAdd();
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const cascaderRef = ref();
const handleChange = value => {
  // console.log("producerList", value);
  const nodes = cascaderRef.value.getCheckedNodes();
  // console.log("找到了当前选中的节点数据===", nodes);
  form.value.receivingAreaDetail = nodes[0].pathLabels.join("");
};

const toPath = () => {
  if (route.query._time && houseValue.value === route.query.factoryId) {
    router.push({
      path: "/procure/outbound/select-prod",
      query: { factoryId: houseValue.value, _time: route.query._time }
    });
  } else {
    _isOpenClear.value = true;
  }
};
const returnSubmitClear = () => {
  router.push({
    path: "/procure/outbound/select-prod",
    query: { factoryId: houseValue.value, _time: new Date().getTime() }
  });
};

const clickDel = row => {
  delTempProductSku({
    code: route.query._time,
    skuId: row.skuId
  }).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: "移除成功！",
        type: "success"
      });
      getList();
    }
  });
  // console.log("删除暂存数据", row);
};

const getName = code => {
  return useCodeArrStore().getDictName("shop_unit", code);
};

//确认出库
const submit = type => {
  if (type === 1) {
    //确认出库
    formRef.value.validate((valid, fields) => {
      if (valid) {
        if (!psValue.value) {
          return ElMessage({
            message: "请选择配送人员！",
            type: "error"
          });
        }
        deliveryFun(type);
      } else {
        console.log("error submit!", fields);
      }
    });
  } else {
    //撤销出库
    deliveryFun(type);
  }
};
const deliveryFun = type => {
  const jdInfo = secondCustomerRef.value.getData();
  const params = {
    type: type, //1：确认出库 2：撤销出库
    deliveryId: route.query.deliveryId, //出库id
    expectStockTime: ckTime.value, //期望出库日期
    delivererName: psName.value, //配送人name
    delivererId: psValue.value, //配送人id
    remark: detail.value.remark, //出库备注
    ...form.value,
    receivingAreaIds: String(form.value.receivingAreaIds),
    customerName: detail.value.customerName, //用户姓名
    customerMobileCode: detail.value.customerMobileCode, //用户电话
    deliveryReqChildList: list.value,
    secondmentCustomerId: jdInfo?.customerId || "", //借调客户id
    secondmentCustomerName: jdInfo?.receivingName || "", //借调客户名称
    secondmentCustomerPhone: jdInfo?.receivingMobile || "", //借调客户号码
    secondmentCustomerAddress: jdInfo?.address || "", //借调客户地址
    secondmentCustomerRemark: jdInfo?.secondmentCustomerRemark || "" //借调客户备注
  };
  // console.log(11111, params);
  delivery(params).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: type === 1 ? "出库成功！" : "撤销出库成功",
        type: "success"
      });
      router.push({ path: "/procure/outbound" });
    }
  });
};

//查询详情数据
const _remark = ref(""); //存一份备注信息，以防取消编辑
const getList = () => {
  createOtherDeliveryOrderDetail({
    deliveryId: route.query.deliveryId
  }).then(res => {
    if (res.code === 200) {
      detail.value = res.data;
      _remark.value = JSON.parse(JSON.stringify(res.data.remark));
      list.value = res.data.childVOList;

      // 期望出库日期
      ckTime.value = res.data.expectStockTime;

      form.value = {
        receivingAddressId: res.data.receivingAddressId,
        receivingName: res.data.receivingName,
        receivingMobile: res.data.receivingMobile,
        receivingAreaIds: res.data.receivingAreaIds ? res.data.receivingAreaIds.split(",").map(Number) : [],
        receivingAddress: res.data.receivingAddress,
        receivingAreaDetail: res.data.receivingAreaDetail
      };
    }
  });
};
//拼接商品的sku规格
const getSpes = properties => {
  if (!properties) return "-";
  const arr = JSON.parse(properties) || [];
  if (arr.length > 1) {
    const str = arr.reduce((a, b) => {
      return a.specificationVal + "+" + b.specificationVal;
    });
    return str;
  } else if (arr.length === 1) {
    return arr[0].specificationVal;
  } else {
    return "-";
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
.divider {
  border-bottom: 1px solid #e2e8f0;
  margin: 20px -20px;
}
.procure-outbound-put {
  height: calc(100% - 64px);
  overflow-y: auto;
  padding: 0 20px 64px 20px;
  position: relative;

  .search-wrap {
    padding: 20px;
    overflow-x: hidden;
    background-color: #f6f8fa;
  }

  .info {
    position: sticky;
    top: 0;
    background-color: white;
    z-index: 22;
    & > div {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 14px 0;
      border-bottom: 1px solid #e2e8f0;
    }
    & > div > div {
      display: flex;
    }
    .left {
      h3 {
        &.green {
          color: #14c85c;
        }
        &.gray {
          color: #86909c;
        }
        &.orange {
          color: #ff9900;
        }
      }
      .creater {
        color: #1a1a1a;
        font-weight: bold;
      }
    }
  }
  .content {
    height: calc(100% - 75px);
    :deep(.el-aside) {
      flex: 1;
      padding: 20px 20px 20px 0;
      header {
        display: flex;
        justify-content: space-between;
        margin-bottom: 18px;
        .supper {
          flex: 1;
          display: flex;
          align-items: center;
          padding-right: 20px;
          p {
            width: 100%;
            color: #86909c;
            font-size: 18px;
            b {
              color: #3d3d3d;
              font-weight: normal;
            }
          }
          .el-select {
            flex: 1;
          }
        }
      }
      .products-list {
        .table-header {
          background-color: #f2f6fc;
          margin-bottom: 10px;
        }
        .table-body {
          .list-item {
            margin-bottom: 10px;
            & > div {
              border: 1px solid #e1e6ed;
              display: flex;
              // align-items: center;
              &:not(:first-of-type) {
                border-left: none;
              }
              &:not(:last-of-type) {
                & > div:not(:last-of-type) {
                  border-right: 1px solid #e1e6ed;
                }
              }
              & > div {
                display: flex;
                align-items: center;
              }
            }
            .col1 {
              & > div {
                display: flex;
              }

              .left {
                img {
                  width: 80px;
                  height: 80px;
                  border-radius: 4px;
                }
              }
              .right {
                padding-left: 18px;
                .name {
                  font-size: 14px;
                  color: #3d3d3d;
                  margin-bottom: 5px;
                }
                p {
                  font-size: 12px;
                  color: #86909c;
                  margin-bottom: 5px;
                }
              }
            }
            .tips {
              display: flex;
              padding: 16px 14px;
              border-top: none;
              border-left: 1px solid #e1e6ed !important;
              p.label {
                width: 38px;
              }
              .el-input {
                flex: 1;
                .el-input__wrapper {
                  background-color: #f2f3f5;
                }
              }
            }
          }
        }
        .table-header,
        .table-body {
          & > div > div:first-of-type {
            display: flex;
            justify-content: space-between;
            & > div {
              padding: 14px 20px;
              &.col1 {
                // width: 45%;
                flex: 1;
              }
              &.col2,
              &.col4,
              &.col7,
              &.col8 {
                width: 80px;
                box-sizing: border-box;
              }
              &.col3 {
                width: 140px;
                box-sizing: border-box;
              }
              &.col5,
              &.col6 {
                width: 125px;
                box-sizing: border-box;
              }
            }
          }
        }
      }
    }
    :deep(.el-main) {
      width: 300px;
      flex: none;
      background-color: #f6f8fa;
      border-left: 1px solid #e2e8f0;
      .ck-time,
      .ps-people {
        p {
          width: 120px;
          margin-bottom: 10px;
        }
        .el-select {
          flex: 1;
        }
      }
      .ps-people {
        & > div {
          display: flex;
          .el-button {
            font-size: 12px;
          }
        }
      }
      .kh-info {
        h3 {
          color: #86909c;
          font-weight: normal;
          margin: 20px 0 16px 0;
        }
        p {
          color: #86909c;
          margin-bottom: 10px;
        }
        b {
          font-weight: normal;
          color: #1a1a1a;
        }
      }
      .sh-info {
        & > p {
          font-size: 16px;
          color: #86909c;
          margin-bottom: 10px;
        }
        .sh-address {
          display: flex;
          justify-content: space-between;
        }
        .el-form-item {
          flex-direction: column;
          span {
            line-height: 20px;
          }
        }
        .el-form-item__label-wrap {
          margin-left: 0 !important;
          .el-form-item__label {
            color: #86909c;
          }
        }
      }
      .ck-tips {
        p.label {
          color: #4e5969;
          margin-bottom: 16px;
        }
      }
    }
  }
  .action-wrap {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
    height: 64px;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    box-shadow: 0px -3px 10px 0px rgba(4, 24, 48, 0.1);
  }
}
</style>
